/********************************************************************************
 *	Copyright 2011 Gerry Weirich
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *	$Id$
 ********************************************************************************/

package ch.rgw.cybert.persist;

import java.util.List;

import org.ektorp.CouchDbConnector;
import org.ektorp.UpdateConflictException;
import org.ektorp.support.CouchDbRepositorySupport;
import org.ektorp.support.View;

import ch.rgw.cybert.Node;

@View(name = "all", map = "function(doc) { if (doc.type == 'Node' ) emit( null, doc._id )}")
public class NodeRepository extends CouchDbRepositorySupport<NodeWrapper> {

	public NodeRepository(CouchDbConnector cdb) {
		super(NodeWrapper.class, cdb);
		initStandardDesignDocument();
	}

	public void putNodes(List<Node> knols) {
		for (Node knol : knols) {
			NodeWrapper kw = new NodeWrapper(knol);
			if (kw.getRevision() == null) {
				add(kw);
			} else {
				updateNode(kw);
			}
			knol.setRevision(kw.getRevision());
		}
	}

	private void updateNode(NodeWrapper knol){
		try {
			update(knol);
		} catch (UpdateConflictException uce) {
			NodeWrapper kNew=get(knol.getId());
			kNew.merge(knol);
			updateNode(kNew);
		}		
	}
}
